import React from 'react'
import ReactDOM from 'react-dom'
import Task from './Task'
import { Tasks } from '../api/tasks'
import { withTracker } from 'meteor/react-meteor-data'
import AccountsUIWrapper from './AccountsUIWrapper';
class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            hideComplete: false
        }
    }
    renderTasks() {
        let filterTasks = this.props.tasks
        if (this.state.hideComplete) {
            filterTasks = filterTasks.filter(task => !task.checked)
        }
        return filterTasks.map((task) => (<Task key={task._id} task={task} />))
    }
    handleSubmit(e) {
        e.preventDefault()
        let item = ReactDOM.findDOMNode(this.refs.todoItem).value.trim()
        Meteor.call('tasks.insert', item)
    }
    toggleHideCompleted() {
        this.setState({
            hideComplete: !this.state.hideComplete
        })
    }
    render() {
        return (<div>
            <div className='container'>
                <header>
                    <h2>to do list {this.props.incompleteTaskCount}</h2>
                </header>
                <label className="hide-completed">
                    <input
                        type="checkbox"
                        readOnly
                        checked={this.state.hideCompleted}
                        onClick={this.toggleHideCompleted.bind(this)}
                    />
                    Hide Completed Tasks
                 </label>
                <AccountsUIWrapper />
                {
                    this.props.currentUser ? <form className="new-task" onSubmit={this.handleSubmit.bind(this)}>
                        <input type='text' ref='todoItem' placeholder='add item' />
                    </form> : ''
                }
                <ul>
                    {this.renderTasks()}
                </ul>
            </div>
        </div>)
    }
}
export default withTracker(() => {
    return {
        tasks: Tasks.find({}, { sort: { createdAt: -1 } }).fetch(),
        incompleteTaskCount: Tasks.find({ checked: { $ne: true } }).count(),
        currentUser: Meteor.user()
    }
})(App)